package com.example.ibsp_demo.controller.search;

import com.example.ibsp_demo.api.ApiMessage;
import com.example.ibsp_demo.service.ISearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/search")
public class SearchController {

    @Autowired
    private ISearchService searchService;

    /**
     * 统一搜索接口
     * @param type 搜索类型：1-用户，2-帖子/内容,3-热点
     * @param keyword 搜索关键词
     * @return 标准化API响应
     */
    @GetMapping("/unified")
    public ApiMessage<Object> unifiedSearch(
            @RequestParam int type,
            @RequestParam String keyword) {
        try {
            // 参数校验
            if (keyword == null || keyword.trim().isEmpty()) {
                return ApiMessage.fail(400, "搜索关键词不能为空");
            }
            if (type < 1 || type > 3) {
                return ApiMessage.fail(400, "无效的搜索类型");
            }

            Object result = searchService.unifiedSearch(type, keyword);
            return ApiMessage.success(result);
        } catch (Exception e) {
            return ApiMessage.fail(500, "搜索失败: " + e.getMessage());
        }
    }

    /**
     * 获取搜索联想结果
     * @param keyword 搜索关键词
     * @return 标准化API响应
     */
    @GetMapping("/suggestions")
    public ApiMessage<List<String>> getSuggestions(@RequestParam String keyword) {
        try {
            // 参数校验
            if (keyword == null || keyword.trim().isEmpty()) {
                return ApiMessage.success(List.of()); // 空关键词返回空列表
            }

            List<String> suggestions = searchService.getSuggestions(keyword);
            return ApiMessage.success(suggestions);
        } catch (Exception e) {
            return ApiMessage.fail(500, "获取联想建议失败: " + e.getMessage());
        }
    }
}